package com.itheima.stock.Thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock : 类似于synchronized 但是lock是一个接口
 *     lock 可以自动加锁和解锁
 */
public class LockDemo {
    public static void main(String[] args) {
        new Thread(new MyThread2(),"线程1").start();
        new Thread(new MyThread2(),"线程2").start();
        new Thread(new MyThread2(),"线程3").start();
    }

    public static class MyThread2 extends Thread {
        static private int tickets = 0;
        static Lock lock = new ReentrantLock();


        public void run() {
            long start1 = System.currentTimeMillis();
            while (true) {
                //synchronized (Synchronnized.MyThread.class) { //代码运行到这会加锁

                lock.lock();
                try {
                    if (tickets < 1000) {
                            Thread.sleep(1);
                        tickets++;
                        System.out.println(Thread.currentThread().getName() + "买的第" + tickets + "张票");
                    } else {
                        break;
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
                //}// 代码运行到这会解锁
            }
            System.out.println("程序运行时间：" + (System.currentTimeMillis() - start1));
        }
    }

}
